import datetime
import json

import requests
from flask import Blueprint, render_template, request
from flask_login import current_user
from applications.common.curd import model_to_dicts
from applications.common.helper import ModelFilter
from applications.common.utils.http import table_api, fail_api, success_api
from applications.common.utils.rights import authorize
from applications.common.utils.validate import str_escape
from applications.extensions import db
from sqlalchemy import desc
from applications.models import WalmartUser, WalmartMsgResult
from applications.schemas import WalmartUserOutSchema

walmart_user = Blueprint('walmartUser', __name__, url_prefix='/walmart/user')


# 用户管理
@walmart_user.get('/')
@authorize("walmart:user:main")
def main():
    return render_template('walmart/user/main.html')


#   用户分页查询
@walmart_user.get('/data')
@authorize("walmart:user:main")
def data():
    # 获取请求参数
    name = str_escape(request.args.get("name"))
    phone = str_escape(request.args.get('phone'))
    # 查询参数构造
    mf = ModelFilter()
    if name:
        mf.contains(field_name="name", value=name)
    if phone:
        mf.contains(field_name="phone", value=phone)

    create_id = current_user.id
    # 非超级管理员只能查询当前用户创建的账号
    if create_id != 1:
        mf.exact(field_name="create_id", value=create_id)
    # orm查询
    # 使用分页获取data需要.items
    user = WalmartUser.query.filter(mf.get_filter(WalmartUser)).order_by(desc(WalmartUser.id)).layui_paginate()
    count = user.total
    # 返回api
    return table_api(data=model_to_dicts(schema=WalmartUserOutSchema, data=user.items), count=count)


# 用户增加
@walmart_user.get('/add')
@authorize("walmart:user:add", log=True)
def add():
    return render_template('walmart/user/add.html')


@walmart_user.post('/save')
@authorize("walmart:user:add", log=True)
def save():
    req_json = request.json
    name = str_escape(req_json.get("name"))
    phone = str_escape(req_json.get('phone'))

    if not name or not phone:
        return fail_api(msg="账号信息不得为空")

    user_data = WalmartUser.query.filter_by(phone=phone).first()
    if user_data is not None:
        return fail_api(msg="该账号已存在")

    create_id = current_user.id
    user = WalmartUser(name=name, phone=phone, create_id=create_id)

    db.session.add(user)
    db.session.commit()
    return success_api(msg="增加成功")


# 删除用户
@walmart_user.delete('/remove/<int:id>')
@authorize("walmart:user:remove", log=True)
def delete(id):
    res = WalmartUser.query.filter_by(id=id).delete()
    if not res:
        return fail_api(msg="删除失败")
    db.session.commit()
    return success_api(msg="删除成功")


# 批量删除
@walmart_user.delete('/batchRemove')
@authorize("walmart:user:remove", log=True)
def batch_remove():
    ids = request.form.getlist('ids[]')
    for id in ids:
        res = WalmartUser.query.filter_by(id=id).delete()
        if not res:
            return fail_api(msg="批量删除失败")
    db.session.commit()
    return success_api(msg="批量删除成功")


@walmart_user.get('/setToken')
@authorize("walmart:user:getMsg", log=True)
def set_token():
    return render_template('walmart/user/token.html')


# 批量获取沃尔玛短信
@walmart_user.post('/batchGetMsg')
@authorize("walmart:user:getMsg", log=True)
def batch_get_msg():
    req_json = request.json
    token = str_escape(req_json.get("token"))

    if not token:
        return fail_api("token 不能为空，找老王")

    create_id = current_user.id

    if create_id != 1:
        users = WalmartUser.query.filter_by(create_id=create_id)
    else:
        users = WalmartUser.query.filter()

    if not users.first():
        return fail_api(msg="请先添加账号信息")

    batch_no = datetime.datetime.now().strftime("%Y%m%d%H%M%S")

    walmart_msg_result_array = []
    print(batch_no)
    num = 0
    for user in users:
        result = get_msg(user.phone, token)
        walmart_msg_result = WalmartMsgResult(batch_no=batch_no, name=user.name, phone=user.phone, msg_result=result,
                                              create_id=create_id)
        walmart_msg_result_array.append(walmart_msg_result)

        # 计算中签数
        rest_json = json.loads(result)
        if rest_json['code'] == 1:
            num += 1
    db.session.add_all(walmart_msg_result_array)
    db.session.commit()

    # 获取本次中签数
    return success_api(msg='本次中签：{} 人，请至【短信记录】查看'.format(num))


# 获取沃尔玛短信
def get_msg(phone, token):
    inline_object = {"appName": "WMFSMINI", "source": "WMFS", "version": "1.0", "format": "json", "sign": "123",
                     "timestamp": "1681296893", "param": {"mobile": phone}}
    headers = {
        "Accept": "application/json",
        "Content-Type": "application/json",
        "Host": "moutai.ghsmpwalmart.com",
        "Connection": "keep-alive",
        "Content-Length": "141",
        "token-fsapi": token,
        "content-type": "application/json",
        "Accept-Encoding": "gzip,compress,br,deflate",
        "User-Agent": "Mozilla/5.0 (iPhone; CPU iPhone OS 16_2 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E148 MicroMessenger/8.0.34(0x18002231) NetType/WIFI Language/zh_CN",
        "Referer": "https://servicewechat.com/wxab43dc9ff2b2d31c/10/page-frame.html"
    }

    response = requests.post('https://moutai.ghsmpwalmart.com/fsapiv3/mini/grantcode', json=inline_object,
                             headers=headers)
    print('手机号码：' + phone + ', Response body is : ' + response.text)
    return response.text
